package deibay.server.frontend.communication.clients;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.messages.Message;
import deibay.util.IClosable;
import deibay.util.ParserXML;

public class UDPService implements IClosable{

	private DatagramSocket udpSocket;	
	private MulticastSocket multicastSocket;
	private boolean keepAlive = true;
	private DataOutputStream os = null;	

	private final int MULTICAST_PORT = 32010;
	private final String GROUP_IP = "228.5.6.7";
	
	public UDPService() {
		try {
			udpSocket = new DatagramSocket();			
			multicastSocket = new MulticastSocket(MULTICAST_PORT);
			InetAddress group = InetAddress.getByName(GROUP_IP);
			multicastSocket.joinGroup(group);			
			DeibayLogger.getInstance().getLog().log(Level.INFO, "UDPService a executar! ("+GROUP_IP+": " + MULTICAST_PORT + ")\n");
		} catch (UnknownHostException e) {		
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao executar UDPService. "+e.getLocalizedMessage()+"\n");
		} catch (IOException e) {			
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao executar UDPService. "+e.getLocalizedMessage()+"\n");
		}
	}

	public void sendMessage(Message message){
		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024);	       
			os = new DataOutputStream(new BufferedOutputStream(byteStream));

			os.flush(); 
			os.writeUTF(ParserXML.getInstance().parseMessageToXML(message)); 
			os.flush(); 
			byte[] sendBuf = byteStream.toByteArray(); 
			DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, InetAddress.getByName(GROUP_IP), MULTICAST_PORT); 
			DeibayLogger.getInstance().getLog().log(Level.WARNING, "UDP: A enviar '" + message.toString()+"'.\n");
			udpSocket.send(packet); 
			os.close(); 
		} catch (IOException e) {			
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Erro ao enviar mensagem de publicidade.\n");
		} 
	}		

	public void close()
	{							
		udpSocket.close();								
	}	
		
}
